<template>
  <el-select :placeholder="placeholder" v-model="data" style="width: 150px;" class="filter-item">
    <el-option v-for="item in dataList" :key="item.id" :label="item[label]" :value="item[feild]"/>
  </el-select>
</template>

<script>

import request from '@/utils/request'

export default {
  name: 'AutoSelect',
  props: {
    // url
    url: {
      type: String,
      required: true
    },
    // 提示内容
    placeholder: {
      type: String,
      default: '请选择'
    },
    // 显示内容
    label: {
      type: String,
      default: ''
    },
    // 绑定数据内容
    feild: {
      type: String,
      default: ''
    },
    // v-model 绑定内容
    value: {
      type: String | Object,
      default: ''
    }
  },
  data() {
    return {
      dataList: {},
      data: ''
    }
  },
  watch: {
    data: function(val, oldVal) {
      this.updateValue(val)
    },
    value: function(val, oldVal) {
      if (val !== this.data) {
        this.data = val
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
  },
  methods: {
    updateValue(val) {
      this.$emit('input', val)
    },
    getList() {
      request({
        url: this.url,
        method: 'post'
      }).then(response => {
        if (response.success) {
          this.dataList = response.data
        } else {
          this.dataList = 'loading error'
        }
        if (undefined !== this.value && this.value !== '') {
          this.data = this.value
        }
      }).catch(e => {
        console.log(e)
        this.dataList = 'loading error'
      })
    }
  }
}
</script>

<style scoped>

</style>
